package com.topway.dsmflex.ui.composite.synchro;

import java.io.IOException;
import java.util.List;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.jdom.JDOMException;

import com.Consts;
import com.topway.dsmflex.Alert;
import com.topway.dsmflex.Log;
import com.topway.dsmflex.model.synchro.DataColumnBean;
import com.topway.dsmflex.model.synchro.DataFileBean;
import com.topway.dsmflex.services.synchro.FileServices;
import com.topway.dsmflex.ui.contentProvider.TableContentProvider;
import com.topway.dsmflex.ui.dialog.ExpressionDialog;
import com.topway.dsmflex.util.XmlEditUtil;

public class AddFileSynchro extends Dialog {

	protected Object result;
	protected Shell shell;
	private Text txtName;
	private DataFileBean fileBean;


	   private ComboBoxCellEditor comTargetColumnName;
	   private String [] targetTables  = new String[]{};
	   private String [] targetColumns  = new String[]{};
	   private String [] targetSource = new String[]{};
	   
	   private FileServices fileServices = null;
	   private 	Combo cboTargetSource;
	   private 	Combo cboOperator;
	   private 	StyledText txtTargetExecuteSql;
	   private 	Combo cboTargetTable;
	   private Text txtNterval;
	   private TableViewer tvInputMeta;
	   private Button checkEnabled;
		private Spinner spStartRow;
		private Combo cboFileType;
		private Combo cboSourceOperator;
	   
	   private boolean flag= false;
	   private String btnType = "";
	/**
	 * Create the dialog.
	 * @param parentble
	 * @param style
	 */
	public AddFileSynchro(Shell parent, int style,DataFileBean fileBean) {
		super(parent, style);
		this.fileBean = fileBean;
	}

	   public int initForm() {
		   this.fileServices = FileServices.getFileServices();
		      try {
		    	  targetSource = XmlEditUtil.getDataSources();
				} catch (JDOMException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		      cboOperator.setItems(Consts.TABLE_OPERATOR);
			   cboTargetSource.setItems(targetSource);
				if(null==fileBean)
				{
					flag = true;
					shell.setText("添加文件配置");
					this.fileBean = new DataFileBean();
				}
				else
				{
					InitDataTableBean();
					shell.setText("修改文件配置["+fileBean.getName()+"]");
				}
				   if(shell.getText().equals("添加文件配置"))
				   {
					   cboOperator.select(1);
					   cboTargetSource.select(0);	
				   }
				 return 1;
	   }
	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		
		initForm();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return fileBean;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
	    shell = new Shell(getParent(),SWT.DIALOG_TRIM  );
		shell.setSize(539, 430);
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));
	    shell.setLocation(getParentLocation());
	    
		SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
		
		Group grpSql = new Group(sashForm, SWT.NONE);
		grpSql.setLayout(null);
		
		Label lblName = new Label(grpSql, SWT.NONE);
		lblName.setBounds(92, 23, 36, 12);
		lblName.setText("名称：");
		
		txtName = new Text(grpSql, SWT.BORDER);
		txtName.setBounds(134, 20, 184, 18);
		
		Label lblFolder = new Label(grpSql, SWT.NONE);
		lblFolder.setBounds(68, 54, 60, 12);
		lblFolder.setText("文件目录：");
		
	
		cboTargetSource = new Combo(grpSql, SWT.NONE);
		cboTargetSource.setBounds(134, 77, 106, 20);
		cboTargetSource.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				if(null!=cboTargetSource&&!cboTargetSource.getText().equals(""))
				{
					fileBean.setDsTarget(cboTargetSource.getText());
					targetTables =  fileServices.getTargetTablesByDb(fileBean);
					cboTargetTable.setItems(targetTables);
				}
			}
		});
		
		Label label_2 = new Label(grpSql, SWT.NONE);
		label_2.setBounds(56, 80, 72, 12);
		label_2.setText("目标数据源：");
		
		Label label_3 = new Label(grpSql, SWT.NONE);
		label_3.setBounds(68, 107, 60, 12);
		label_3.setText("目标操作：");
		

		cboOperator = new Combo(grpSql, SWT.NONE);
		cboOperator.setBounds(134, 104, 106, 20);
		

		
		txtTargetExecuteSql = new StyledText(grpSql, SWT.BORDER|SWT.V_SCROLL);
		txtTargetExecuteSql.setBounds(133, 157, 346, 49);
		
		Label label_6 = new Label(grpSql, SWT.NONE);
		label_6.setBounds(43, 157, 84, 12);
		label_6.setText("目标后行语句：");
		
		Label label_7 = new Label(grpSql, SWT.NONE);
		label_7.setBounds(247, 80, 48, 12);
		label_7.setText("目标表：");
		

		
		cboTargetTable = new Combo(grpSql, SWT.NONE);
		cboTargetTable.setBounds(300, 78, 179, 20);
		cboTargetTable.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				if(null!=cboTargetTable&&!cboTargetTable.getText().equals(""))
				{
					fileBean.setTableNameTarget(cboTargetTable.getText());
				}
			}
		});
		
		Label label_8 = new Label(grpSql, SWT.NONE);
		label_8.setBounds(336, 24, 36, 12);
		label_8.setText("频率：");
		
		Button button = new Button(grpSql, SWT.NONE);
		button.setBounds(158, 236, 60, 22);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(null!=fileBean.getDsTarget())
				{
					if(null==fileBean.getTableNameTarget()||fileBean.getTableNameTarget().equals(""))
						return;
		            try {
		            	List<DataColumnBean> list = fileBean.getDataColumnBean();
		            	//if(null==list||list.size()==0)//不读从数据库中获取最新的字段信息
		            		list = (List<DataColumnBean>) fileServices.getColumnInfo(fileBean);
		            	
		            	targetColumns =  fileServices.getColumnInfoArray(fileBean);
					    	  comTargetColumnName.setItems(targetColumns);
					      
//					      if(!fileBean.getTableNameSource().equals(fileBean.getTableNameTarget()))
//					      {
//					    	  for (DataColumnBean _dc : list) {
//					    		  for (int i = 0; i < targetColumns.length; i++) {
//					    			  if(_dc.getColumnNameTarget().equals(targetColumns[i]))
//					    			  {
//					    				  _dc.setColumnNameTarget(targetColumns[i]);
//					    				  break;
//					    			  }else if(!_dc.getColumnNameTarget().equals("")&& !_dc.getColumnNameTarget().equals(targetColumns[i]))
//					    			  {
//					    				 break;
//					    			  }else
//					    				  _dc.setColumnNameTarget("");
//									}  
//					    	  }
//					      }
					    	  tvInputMeta.setInput(null);
		            	tvInputMeta.setInput(list);
					} catch (Exception ee) {
						ee.printStackTrace();
						Log.error(ee.getMessage());
					}	
					
				}
			}
		});
		button.setText("查询");
		
		Button btnNewButton = new Button(grpSql, SWT.NONE);
		btnNewButton.setBounds(246, 236, 71, 22);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnType="SUBMIT";
				int reuslt = SaveDataTableBean();
				if(reuslt>0)
				shell.close();
			}

		});
		btnNewButton.setText("确定");
		
		txtNterval = new Text(grpSql, SWT.BORDER);
		txtNterval.setBounds(378, 21, 60, 18);
		txtNterval.setText("10.0");
		
		Label label_9 = new Label(grpSql, SWT.NONE);
		label_9.setText("（分）");
		label_9.setBounds(445, 24, 36, 12);
		
		Button btnNewButton_1 = new Button(grpSql, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
					fileBean=null;
					shell.close();
			}
		});
		btnNewButton_1.setBounds(342, 236, 72, 22);
		btnNewButton_1.setText("取消");
		
		checkEnabled = new Button(grpSql, SWT.CHECK);
		checkEnabled.setSelection(true);
		checkEnabled.setBounds(59, 239, 93, 16);
		checkEnabled.setText("激活");
		
		txtFolder = new Text(grpSql, SWT.BORDER);
		txtFolder.setBounds(134, 51, 280, 18);
		
		Button btnSelect = new Button(grpSql, SWT.NONE);
		btnSelect.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				folderDig(new Shell());
				
			}
		});
		btnSelect.setBounds(420, 49, 60, 22);
		btnSelect.setText("选择目录");
		
		txtSeparate = new Text(grpSql, SWT.BORDER);
		txtSeparate.setBounds(306, 131, 60, 18);
		
		Label label = new Label(grpSql, SWT.NONE);
		label.setText("分隔符：");
		label.setBounds(253, 134, 49, 12);
		
		Label label_1 = new Label(grpSql, SWT.NONE);
		label_1.setText("开始行：");
		label_1.setBounds(379, 134, 49, 12);
		
		spStartRow= new Spinner(grpSql, SWT.BORDER);
		spStartRow.setBounds(431, 130, 48, 21);
		
		cboSourceOperator = new Combo(grpSql, SWT.NONE);
		cboSourceOperator.setItems(new String[] {"", "DELETE"});
		cboSourceOperator.setBounds(356, 103, 123, 20);
		
		Label label_4 = new Label(grpSql, SWT.NONE);
		label_4.setText("源文件操作：");
		label_4.setBounds(253, 107, 70, 12);
		
		
	
		cboFileType = new Combo(grpSql, SWT.READ_ONLY);
		cboFileType.setItems(new String[] {"EXCEL", ".TXT"});
		cboFileType.setBounds(134, 131, 106, 20);
		
		Label lblfileType = new Label(grpSql, SWT.NONE);
		lblfileType.setText("文件类型：");
		lblfileType.setBounds(68, 134, 60, 12);
		
		txtSaveFilePath = new Text(grpSql, SWT.BORDER);
		txtSaveFilePath.setBounds(134, 212, 280, 18);
		
		Label label_5 = new Label(grpSql, SWT.NONE);
		label_5.setText("操作后文件保存目录：");
		label_5.setBounds(10, 215, 118, 12);
		
		Button button_1 = new Button(grpSql, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				saveFolderDig(new Shell());
			}
		});
		button_1.setText("选择目录");
		button_1.setBounds(420, 210, 60, 22);
		
		Label lbln = new Label(grpSql, SWT.NONE);
		lbln.setText("变量引用{0}-{n}");
		lbln.setBounds(430, 241, 93, 17);
		
		tvInputMeta = new TableViewer(sashForm, SWT.BORDER | SWT.FULL_SELECTION);
	      tvInputMeta.setContentProvider(new TableContentProvider());
	      tvInputMeta.setLabelProvider(new InputMetaLabelProvider());
	      tvInputMeta.setColumnProperties(INPUTMETAS);
	      Table tblInputMeta = tvInputMeta.getTable();
	     
			
	      tblInputMeta.setLinesVisible(true);
	      tblInputMeta.setHeaderVisible(true);
	      CellEditor[] cellEditor2 = new CellEditor[3];
	      cellEditor2[0] = new ComboBoxCellEditor(tblInputMeta,Consts.TABLE_KEY_LABEL, SWT.READ_ONLY);
	      comTargetColumnName = new ComboBoxCellEditor(tblInputMeta,targetColumns, SWT.READ_ONLY);
	      cellEditor2[1] =comTargetColumnName;
	      cellEditor2[2] = new ExpressionCellEditor(tblInputMeta);
	      
	      tvInputMeta.setCellEditors(cellEditor2);
	      tvInputMeta.setCellModifier(new InputsCellModifier(tvInputMeta));

	      final TableColumn colIsKey = new TableColumn(tblInputMeta, SWT.NONE);
	      colIsKey.setWidth(70);
	      colIsKey.setText("主键");

	      final TableColumn colNameTarget = new TableColumn(tblInputMeta, SWT.NONE);
	      colNameTarget.setWidth(110);
	      colNameTarget.setText("目标字段名");
	      
		    final TableColumn colExpress = new TableColumn(tblInputMeta, SWT.NONE);
		    colExpress.setWidth(207);
		    colExpress.setText("表达式");
		    sashForm.setWeights(new int[] {271, 131});
		    
		    
		    
		    shell.addShellListener(new ShellAdapter() {
	            public void shellClosed(ShellEvent e) {
	            	if(btnType.equals(""))
	            	fileBean = null;
						e.doit=true;
	            }
		    });
		    

	}
	
	private void InitDataTableBean()
	{

		this.txtName.setText(null==this.fileBean.getName()?"":this.fileBean.getName());
//		this.fileBean.getSourceDataSource(null);
//		this.fileBean.getTargetDataSource(null);
		this.txtFolder.setText(null==this.fileBean.getSourceFilePath()?"":this.fileBean.getSourceFilePath());  
		cboTargetSource.setText(this.fileBean.getDsTarget());
		cboTargetTable.setText(this.fileBean.getTableNameTarget());
		checkEnabled.setSelection(this.fileBean.getEnabled()==1);
		txtSaveFilePath.setText(null==this.fileBean.getSourceFileSavePath()?"":this.fileBean.getSourceFileSavePath());
		spStartRow.setSelection(Integer.parseInt(this.fileBean.getStartRow()));
		cboFileType.setText(this.fileBean.getFileType());
		cboSourceOperator.setText(fileBean.getOperatorSource());
//		this.fileBean.setStartRow(""+spStartRow.getText());
//		this.fileBean.setFileType(cboFileType.getText());
		txtSeparate.setText(null==this.fileBean.getSeparate()?"":this.fileBean.getSeparate());
		
		cboOperator.setText(null==this.fileBean.getOperatorTarget()?"":this.fileBean.getOperatorTarget());
		txtTargetExecuteSql.setText(null==this.fileBean.getTargetExecuteSql()?"":this.fileBean.getTargetExecuteSql());
		txtNterval.setText(""+this.fileBean.getSynchroNterval());
		tvInputMeta.setInput(this.fileBean.getDataColumnBean());
		
	}
	   public Point getParentLocation() {

		      Shell shell = getParent();
		      int x = shell.getLocation().x;
		      int y = shell.getLocation().y;
		      Rectangle rectParent = shell.getBounds();
		      Point size = this.shell.getSize();
		      int xx = x + rectParent.width / 2 - size.x / 2;
		      int yy = y + rectParent.height / 2 - size.y / 2;
		      return new Point(xx, yy);
		   }
	   
	   
	   protected void saveFolderDig(Shell parent){
	       DirectoryDialog folderdlg=new DirectoryDialog(parent); 
	       folderdlg.setText("文件选择");
	       folderdlg.setFilterPath(txtFolder.getText());
	       folderdlg.setMessage("请选择相应的文件夹");
	       String selecteddir=folderdlg.open();
	       if(selecteddir==null){
	           return ;
	       }
	       else{
	           this.txtSaveFilePath.setText(selecteddir);  
	           this.fileBean.setSourceFileSavePath(selecteddir);
	       }                    
	   }
	   
	   
	   protected void folderDig(Shell parent){
	       DirectoryDialog folderdlg=new DirectoryDialog(parent); 
	       folderdlg.setText("文件选择");
	       folderdlg.setFilterPath(txtFolder.getText());
	       folderdlg.setMessage("请选择相应的文件夹");
	       String selecteddir=folderdlg.open();
	       if(selecteddir==null){
	           return ;
	       }
	       else{
	           this.txtFolder.setText(selecteddir);  
	           this.fileBean.setSourceFilePath(selecteddir);
	       }                    
	   }
	   
	public int SaveDataTableBean()
	{
		this.fileBean.setName(this.txtName.getText());
		this.fileBean.setOperatorTarget(cboOperator.getText());
		this.fileBean.setTableNameTarget(cboTargetTable.getText());
		this.fileBean.setSeparate(txtSeparate.getText());
		this.fileBean.setStartRow(""+spStartRow.getText());
		this.fileBean.setFileType(cboFileType.getText());
		
		this.fileBean.setOperatorSource(cboSourceOperator.getText());

		this.fileBean.setTargetExecuteSql(txtTargetExecuteSql.getText());
		this.fileBean.setEnabled(checkEnabled.getSelection()?1:0);
		try {
			this.fileBean.setSynchroNterval(Float.valueOf(txtNterval.getText()));
		} catch (Exception e) {
			Alert.MsgBox("提示", "频率有误，请检查！");
			txtNterval.forceFocus();
			return 0;
		}
		if(null==fileBean.getName()||fileBean.getName().equals(""))
		{
			Alert.MsgBox("提示", "任务名必填，请检查！");
			txtName.forceFocus();
			return 0;
		}
		this.fileBean.setDataColumnBean((List<DataColumnBean>) tvInputMeta.getInput());
		return 1;
		
	}
	
	
	   public static String[] INPUTMETAS = new String[] {"isKey" ,"columnNameTarget","colExpress"};
	   private Text txtFolder;
	   private Text txtSeparate;
	   private Text txtSaveFilePath;

	   class InputsCellModifier implements ICellModifier {
	      private TableViewer tv;

	      public InputsCellModifier(TableViewer tv) {
	         this.tv = tv;
	      }

	      public boolean canModify(Object element, String property) {
	         return true;
	      }

	      public Object getValue(Object element, String property) {
	    	  DataColumnBean o = (DataColumnBean ) element;
	        if (property.equals("isKey")) return getIndex(Consts.TABLE_KEY, o.getIsKey());
	        else if (property.equals("columnNameTarget"))  return getIndex(targetColumns, o.getColumnNameTarget()); 
	        else if (property.equals("colExpress")) return (null==o.getColExpress()?"":o.getColExpress());
	        throw new RuntimeException("错误的列别名:" + property);
	      }

	      private int getIndex(String[] labels, String name) {
	         for (int i = 0; i < labels.length; i++) {
	            if (labels[i].equalsIgnoreCase(name)) return i;
	         }
	         return 0;
	      }

	      public void modify(Object element, String property, Object value) {
	         TableItem item = (TableItem) element;
	         DataColumnBean o = (DataColumnBean ) item.getData();
	          if (property.equals("isKey")) {
		            o.setIsKey(Consts.TABLE_KEY[(Integer) value]);
		         }
	         else  if (property.equals("columnNameTarget")) {
		        		 o.setColumnNameTarget(targetColumns[(Integer) value]);
	        	}
	         else  if (property.equals("colExpress")) {
		            o.setColExpress((String) value);
			     }
	         else {
	             throw new RuntimeException("错误的列别名:" + property);
	          }
	         tv.update(o, null);
	      }
	   }
	   class InputMetaLabelProvider extends LabelProvider implements ITableLabelProvider {
		      public String getColumnText(Object obj, int columnIndex) {
		    	  DataColumnBean dsi = (DataColumnBean )  obj;
		         switch (columnIndex) {
		         case 0:
		        	 return getLabel(Consts.TABLE_KEY_LABEL,Consts.TABLE_KEY,dsi.getIsKey());
		         case 1:
		        	 return dsi.getColumnNameTarget();
		         case 2:
		        	 return dsi.getColExpress();
		         }
		         return null;
		      }
		      
		      private String getLabel(String[] labels, String[] values, String name) {
		         for (int i = 0; i < values.length; i++) {
		            if (values[i].equalsIgnoreCase(name)) return labels[i];
		         }
		         return "";
		      }

		      public String getText(Object element) {
		         return element == null ? "" : element.toString();
		      }

		      public Image getColumnImage(Object obj, int index) {
		         return null;
		      }
		   }

	   
	   class ExpressionCellEditor extends DialogCellEditor {

		      private Table table;

		      public ExpressionCellEditor(Composite parent) {
		         super(parent);
		         this.table = (Table) parent;
		      }
		      protected Object openDialogBox(Control cellEditorWindow) {
		         TableItem[] selectItems = table.getSelection();
		         String exp = "";
		         if (selectItems != null && selectItems.length > 0) exp = ((DataColumnBean) selectItems[0].getData()).getColExpress();
		         ExpressionDialog gcd = new ExpressionDialog(cellEditorWindow.getShell(), null==exp?"":exp);
		         String res = gcd.open();
		         return res;
		      }
		   }
}
